import { EventEmitter } from '../../engine/common/event-emmiter';
import { View } from './view';

export class CanvasView extends View {
  #containerElement: HTMLElement = document.body;

  #isCanvasReadyEmitted = false;
  #canvasElement: HTMLCanvasElement | null = null;

  readonly onAnyKeyPressed = new EventEmitter();
  readonly onCanvasReady = new EventEmitter<HTMLCanvasElement>();

  getCanvasElement(): HTMLCanvasElement | null {
    return this.#canvasElement;
  }

  listenToEvents() {
    this.listenToKeyDown();
  }

  renderHello() {
    this.renderTitle('Нажмите любую клавишу');
  }

  renderVictory() {
    this.renderTitle('Победа');
  }

  renderDefeat() {
    this.renderTitle('Поражение');
  }

  renderCanvas(isLoading: boolean) {
    if (!this.#canvasElement) {
      this.#canvasElement = document.createElement('canvas');
    }

    this.#containerElement.replaceChildren(this.#canvasElement);

    if (isLoading) {
      const h1Element = document.createElement('h1');
      h1Element.textContent = 'Загрузка...';
      this.#containerElement.appendChild(h1Element);

      this.#canvasElement.style.display = 'none';
    } else {
      this.#canvasElement.style.display = 'block';
    }

    if (!this.#isCanvasReadyEmitted) {
      this.#isCanvasReadyEmitted = true;
      this.onCanvasReady.emit(this.#canvasElement);
    }
  }

  private renderTitle(message: string) {
    const h1Element = document.createElement('h1');
    h1Element.textContent = message;

    this.#containerElement.replaceChildren(h1Element);
  }

  private onHandleKeyDown = () => {
    this.stopListeningToKeyDown();
    this.onAnyKeyPressed.emit();
  };

  private listenToKeyDown() {
    document.addEventListener('keydown', this.onHandleKeyDown);
  }

  private stopListeningToKeyDown() {
    document.removeEventListener('keydown', this.onHandleKeyDown);
  }
}
